package com.gsma.calendar.android.ui;

import java.util.Date;
import java.util.StringTokenizer;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.gsma.calendar.android.R;
import com.gsma.calendar.android.db.CalendarGSMAColumns;
import com.gsma.calendar.android.db.CalendarGsmaDBSchema.Tables;
import com.gsma.calendar.android.db.CalendarGsmaQuery;
import com.gsma.calendar.android.db.GlobalEventQuery;
import com.gsma.calendar.android.db.LocalCalendarEventsColumns;
import com.gsma.calendar.android.db.LocalCalendarEventsQuery;
import com.gsma.calendar.android.model.CalendarObject;
import com.gsma.calendar.android.model.LocalCalendarEvents;
import com.gsma.calendar.android.util.CalendarGsmaUtil;
import com.gsma.calendar.android.util.Config;
import com.gsma.calendar.android.util.UpdateScript;

public class SessionDetailActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {

	private TextView title;
	private TextView header_info;
	private long calendar_id_value = 0;
	private String uri_calendar_value = null;
	private Button add_removeButton;
	private long calendar_id;
	private Cursor mCursor;
	private String session_name = null;
	private int event_id_bundle;
	public static final int UPDATE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.session_detail);

		title = (TextView) findViewById(R.id.header_title);
		header_info = (TextView) findViewById(R.id.header_info);
		add_removeButton = (Button) findViewById(R.id.add_full);

		calendar_id = getIntent().getLongExtra(Config.CALENDAR_ID, 0);
		event_id_bundle = getIntent().getIntExtra(Config.EVENT_ID, 0);

	}

	@Override
	protected void onResume() {
		super.onResume();
		Bundle bundle = new Bundle();
		bundle.putInt(Config.EVENT_ID, event_id_bundle);
		getSupportLoaderManager().initLoader(GlobalEventQuery._TOKEN, bundle, this);

		new Runnable() {
			@Override
			public void run() {
				UpdateScript script = new UpdateScript(SessionDetailActivity.this);
				script.runUpdate();
				handler.sendEmptyMessage(UPDATE);
			}
		}.run();

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UPDATE:
				Bundle bundle = new Bundle();
				bundle.putInt(Config.EVENT_ID, event_id_bundle);
				getSupportLoaderManager().destroyLoader(GlobalEventQuery._TOKEN);
				getSupportLoaderManager().initLoader(GlobalEventQuery._TOKEN, bundle, SessionDetailActivity.this);
				break;

			}
		};
	};

	@Override
	protected void onPause() {
		getSupportLoaderManager().destroyLoader(GlobalEventQuery._TOKEN);
		super.onPause();
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		switch (id) {
		case GlobalEventQuery._TOKEN:
			int event_id = bundle.getInt(Config.EVENT_ID);
			return new CursorLoader(SessionDetailActivity.this, CalendarObject.CONTENT_URI, CalendarGsmaQuery.PROJECTION, Tables.CALENDAR_GSMA + "."
					+ CalendarGSMAColumns._ID.getName() + "=?", new String[] { String.valueOf(event_id) }, CalendarObject.START_TIME_SORT);
		default:
			return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		switch (loader.getId()) {
		case GlobalEventQuery._TOKEN:
			if (cursor != null && cursor.moveToFirst()) {
				startManagingCursor(cursor);
				mCursor = cursor;
				session_name = cursor.getString(cursor.getColumnIndex(CalendarGSMAColumns.SESSION.getName()));
				title.setText(session_name);
				StringBuilder sb = new StringBuilder();
				sb.append(session_name);
				String start = Config.sdf.format(new Date(cursor.getLong(cursor.getColumnIndex(CalendarGSMAColumns.START_TIME.getName()))));
				String end = Config.sdf.format(new Date(cursor.getLong(cursor.getColumnIndex(CalendarGSMAColumns.END_TIME.getName()))));
				sb.append(session_name);
				sb.append("\n");
				sb.append(start + " - " + end);
				sb.append("\n");
				sb.append("Location: " + cursor.getString(cursor.getColumnIndex(CalendarGSMAColumns.WHERE.getName())));
				header_info.setText(sb.toString());

				Cursor subCursor = getContentResolver().query(
						LocalCalendarEvents.CONTENT_URI,
						LocalCalendarEventsQuery.PROJECTION,
						LocalCalendarEventsColumns.CALENDAR_ID.getName() + " = " + calendar_id + " AND " + LocalCalendarEventsColumns.SESSION_NAME.getName()
								+ " = '" + session_name + "'", null, null);
				if (cursor != null && subCursor.moveToFirst()) {
					calendar_id_value = subCursor.getLong(LocalCalendarEventsQuery.CALENDAR_ID);
					uri_calendar_value = subCursor.getString(LocalCalendarEventsQuery.URI_EVENT);
					int text = (calendar_id_value == 0 && uri_calendar_value == null) ? R.string.add : R.string.remove;
					add_removeButton.setText(getString(text));
				} else {
					add_removeButton.setText(R.string.add);
				}
				subCursor.close();

			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {

	}

	public void addOrRemoveEvent(View view) {
		ContentValues contentValues = new ContentValues();
		CalendarGsmaUtil calendar = new CalendarGsmaUtil(SessionDetailActivity.this);
		Button button = (Button) view;
		if (button.getText().equals(getString(R.string.add))) {
			if (mCursor != null) {
				Uri uri1 = calendar.makeNewCalendarEntry((int) calendar_id, mCursor);
				uri_calendar_value = uri1.toString();
				contentValues.put(LocalCalendarEventsColumns.CALENDAR_ID.getName(), calendar_id);
				contentValues.put(LocalCalendarEventsColumns.URI_EVENT.getName(), uri_calendar_value);
				contentValues.put(LocalCalendarEventsColumns.SESSION_NAME.getName(), session_name);
				getContentResolver().insert(LocalCalendarEvents.CONTENT_URI, contentValues);
				add_removeButton.setText(getString(R.string.remove));
			}
		} else {
			getContentResolver().delete(
					LocalCalendarEvents.CONTENT_URI,
					LocalCalendarEventsColumns.CALENDAR_ID.getName() + " = " + calendar_id + " AND " + LocalCalendarEventsColumns.SESSION_NAME.getName()
							+ " = '" + session_name + "'", null);
			add_removeButton.setText(getString(R.string.add));
			String id_event = null;
			if (uri_calendar_value != null) {
				StringTokenizer st = new StringTokenizer(uri_calendar_value, "/");

				while (st.hasMoreElements()) {
					id_event = st.nextToken();
				}
			}
			if (id_event != null) {
				int count = calendar.deleteCalendarEntry(Integer.valueOf(id_event));
				Log.e("delete", "" + count);

			}

		}

	}

}
